<?php

require_once 'const/DBConst.php';

class Application_Model_ProductMapper {

    public static function insert($product) {
        $db = Zend_Registry::get("database");
        $date = array(
            C_NAME => $product->getName(),
            C_DESCRIPTION => $product->getDescription(),
            C_TYPE_ID => $product->getTypeID(),
            C_PRICE => $product->getPrice(),
            C_NUM => $product->getNum()
        );
        $db->insert(T_PRODUCT, $date);
        return $db->lastInsertId();
    }

    public static function getNewProducts($size) {
        $db = Zend_Registry::get("database");
        $result = $db->fetchAll("SELECT * FROM " . T_PRODUCT . " ORDER BY ID DESC LIMIT " . $size);
        return $result;
    }

    public static function getHotProducts($size) {
        $db = Zend_Registry::get("database");
        $result = $db->fetchAll("SELECT * FROM " . T_PRODUCT . " ORDER BY BUY_TIMES DESC LIMIT " . $size);
        return $result;
    }

    public static function fetchAll() {
        $db = Zend_Registry::get("database");
        $result = $db->fetchAll("SELECT * FROM " . T_PRODUCT);
        return $result;
    }

    public static function delete($id) {
        $db = Zend_Registry::get("database");
        $db->delete(T_PRODUCT, 'ID=' . $id);
        $path = APPLICATION_PATH . "/../public/upload/" . $id;
        unlink($path);
    }

    public static function update($product) {
        $db = Zend_Registry::get("database");
        $date = array(
            C_NAME => $product->getName(),
            C_DESCRIPTION => $product->getDescription(),
            C_TYPE_ID => $product->getTypeID(),
            C_PRICE => $product->getPrice(),
            C_NUM => $product->getNum()
        );
        $db->update(T_PRODUCT, $date, "ID=" . $product->getId());
    }

    public static function fetchByType($typeID) {
        $db = Zend_Registry::get("database");
        $result = $db->fetchAll("SELECT * FROM " . T_PRODUCT . " WHERE TYPE_ID=" . $typeID);
        return $result;
    }

    public static function fetch($id) {
        $db = Zend_Registry::get("database");
        $result = $db->fetchRow("SELECT * FROM " . T_PRODUCT . " WHERE ID=" . $id);
        return $result;
    }

    public static function buy($productID, $accountID, $num) {
        $db = Zend_Registry::get("database");
        $product = $db->fetchRow("SELECT * FROM PRODUCT WHERE ID=" . $productID);
        $leftNum = $product[C_NUM];
        if ($leftNum >= $num) {
            $date = array(
                C_NUM => ($leftNum - $num),
                C_BUY_TIMES => $product[C_BUY_TIMES] + $num
            );
            $db->update(T_PRODUCT, $date, "ID=" . $productID);
            $order = new Application_Model_Order($num, $accountID, $productID);
            Application_Model_OrderMapper::insert($order);
            return true;
        } else {
            return false;
        }
    }

}

